﻿using com.sun.org.apache.bcel.@internal.generic;
using MongoDB.Driver;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Project.Infrastructure.MongDB
{
    // 安装 MongoDB.Driver  NewGet
    public class MongDBContext<T> where T : class, new()
    {
        public MongoClient db;
        private string database = "AuthorizedServices";
        public MongDBContext()
        {
            string dbConnectoin = "mongodb://auth_services:123456@49.233.140.37:27017/Webdev?authSource=AuthorizedServices";
            db = new MongoClient(dbConnectoin);
        }

        public async Task InsertAsync(T doc, InsertOneOptions options = null)
        {
            string collectionName = typeof(T).Name;
            await db.GetDatabase(database).GetCollection<T>(collectionName).InsertOneAsync(doc, options);
        }

        public async Task<UpdateResult> UpdateAsync(T doc, FilterDefinition<T> filter, UpdateDefinition<T> updateFields)
        {
            string collectionName = typeof(T).Name;
            return await db.GetDatabase(database).GetCollection<T>(collectionName).UpdateOneAsync(filter, updateFields);
        }


        public async Task<IAsyncCursor<T>> GetByFilterAsync(FilterDefinition<T> filter)
        {
            string collectionName = typeof(T).Name;
            return await db.GetDatabase(database).GetCollection<T>(collectionName).FindAsync<T>(filter);
        }

        public async Task<DeleteResult> DeleteAsync(FilterDefinition<T> filter)
        {
            string collectionName = typeof(T).Name;
            return await db.GetDatabase(database).GetCollection<T>(collectionName).DeleteManyAsync(filter);
        }


    }
}
